﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace _TablesManagement
{
    public partial class TablesManagement : UserControl
    {
        public delegate void tableDoubleCLickDeg(int tableid, Table.TableStatus status);
        public event tableDoubleCLickDeg TableDoubleClick;
        private List<PictureEdit> pics = new List<PictureEdit>();

        private bool isMoving, isManager;
        private Table currentTable = null;
        private RADB.DataSetRA.TablesRow currentTableData = null;
        private Size preCursor;

        //public bool ControlPanelVisible { get { return pnlControl.Visible; } set { pnlControl.Visible = value; } }
        public bool IsManager { get { return isManager; } set { isManager = value; ChangeComponentStatus(); } }

        public TablesManagement()
        {
            InitializeComponent();

            LoadStatusPics();

            rdoStatus.Enabled = false;
            rdoStatus.SelectedIndex = 0;
        }

        #region LoadData
        private void LoadStatusPics()
        {
            pics.Add(picAvailable);
            pics.Add(picReserved);
            pics.Add(picWaiting);
            pics.Add(picOccupied);
            pics.Add(picDirty);
            pics.Add(picCleaning);

            foreach (PictureEdit x in pics)
            {
                //string tmp = x.Name.Substring(4);
                x.Image = (Image)MapResource.ResourceManager.GetObject("img" + x.Name.Substring(3));
            }

            foreach (RadioGroupItem x in rdoStatus.Properties.Items)
            {
                x.Value = Enum.Parse(typeof(Table.TableStatus), x.Description);
            }
        }

        public void SetSource(RADB.DataSetRA dataSet, RADB.DataSetRATableAdapters.TablesTableAdapter adapter)
        {
            this.dataSetRA = dataSet;
            this.tablesTableAdapter = adapter;

            tablesTableAdapter.Fill(dataSetRA._Tables);
            this.dataSetRA._Tables.RowChanged += new DataRowChangeEventHandler(_Tables_RowChanged);
            LoadMap();
        }

        void _Tables_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            RADB.DataSetRA.TablesRow tmp = e.Row as RADB.DataSetRA.TablesRow;
            if (tmp.RowState != DataRowState.Detached && pnlControl.Controls[tmp.TableName] != null)
            {
                ((Table)pnlMap.Controls[tmp.TableName]).Status = (Table.TableStatus)tmp.Status;    
            }
            
        }

        private void LoadMap()
        {
            pnlMap.Controls.Clear();
            foreach (RADB.DataSetRA.TablesRow table in dataSetRA._Tables)
            {
                DrawATable(table.TableName, (int)table.PosX, (int)table.PosY, table.Status);
            }
        }
        #endregion

        private void ChangeComponentStatus()
        {
            btnNew.Enabled = isManager;
            btnRemove.Enabled = isManager;
            txtName.Enabled = isManager;
            txtSeats.Enabled = isManager;
            txtNotes.Enabled = isManager;
        }

        private void SetEvent(Table t)
        {
            foreach (Control z in t.Controls)
            {
                z.MouseDown += new MouseEventHandler(Table_MouseDown);
                z.MouseUp += new MouseEventHandler(Table_MouseUp);
                z.MouseMove += new MouseEventHandler(Table_MouseMove);
                z.MouseClick += new MouseEventHandler(Table_MouseClick);
                z.DoubleClick += new EventHandler(Table_DoubleClick);
            }
            t.MouseDown += new MouseEventHandler(Table_MouseDown);
            t.MouseUp += new MouseEventHandler(Table_MouseUp);
            t.MouseMove += new MouseEventHandler(Table_MouseMove);
            t.MouseClick += new MouseEventHandler(Table_MouseClick);
            t.DoubleClick += new EventHandler(Table_DoubleClick);
        }

        void Table_DoubleClick(object sender, EventArgs e)
        {
            if (TableDoubleClick != null)
                TableDoubleClick.Invoke(currentTableData.ID, currentTable.Status);
        }

        private void DrawATable(string name, int x, int y, int status)
        {
            Table t = new Table();
            t.Name = name;
            t.TableName = name;
            pnlMap.Controls.Add(t);
            t.Status = (Table.TableStatus)status;
            t.Location = new Point(x, y);
            t.Size = new Size(120, 70);
            t.Visible = true;
            SetEvent(t);
        }

        private void NewTable(string name)
        {
            DrawATable(name, 1, 1, 1);
            RADB.DataSetRA.TablesRow newRow;
            newRow = dataSetRA._Tables.NewTablesRow();
            newRow.Status = 1;
            newRow.TableName = name;
            newRow.PosX = 1;
            newRow.PosY = 1;
            newRow.NumOfSeats = (int)txtSeats.Value;
            newRow.Note = txtNotes.Text.Trim();

            //update to db
            dataSetRA._Tables.AddTablesRow(newRow);
            tablesTableAdapter.Update(newRow);
        }

        private RADB.DataSetRA.TablesRow GetCurrentTableRow(string name)
        {
            DataRow[] row = dataSetRA._Tables.Select(String.Format("TableName = '{0}'", name));
            if (row.Length == 1)
                return (RADB.DataSetRA.TablesRow)row[0];
            else
                return null;
        }
        #region ButtonEvents
        private void btnNew_Click(object sender, EventArgs e)
        {
            
            if (txtName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Missing the new table's name", "Error", MessageBoxButtons.OK);
                txtName.Focus();
                txtName.SelectAll();
            }
            else if (GetCurrentTableRow(txtName.Text.Trim()) != null)
            {
                MessageBox.Show("The table's name is existed", "Error", MessageBoxButtons.OK);
                txtName.Focus();
                txtName.SelectAll();
            }
            else
            {
                
                NewTable(txtName.Text);
                ResetPanelControl();
                //rdoStatus.SelectedIndex = 0;
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            ResetPanelControl();
            rdoStatus.SelectedIndex = 0;
            if (currentTable != null)
            {
                pnlMap.Controls.Remove(currentTable);
                
                //update to db                

                currentTableData.Delete();

                //if (tablesTableAdapter != null)
                //    tablesTableAdapter.Update(dataSetRA);
                
                currentTable = null;
                currentTableData = null;
            }
        }

        private void ResetPanelControl()
        {
            txtName.Text = "";
            txtSeats.Value = 1;
            txtNotes.Text = "";
            rdoStatus.Enabled = false;
        }
        #endregion

        #region TableEvents


        private void Table_MouseDown(object sender, MouseEventArgs e)
        {
            isMoving = isManager;
            preCursor = new Size(e.Location);
        }

        private void Table_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMoving)
            {
                ((Table)((Control)sender).GetContainerControl()).Location +=
                    new Size(e.Location - preCursor);
            }
        }

        private void Table_MouseUp(object sender, MouseEventArgs e)
        {
            isMoving = false;
        }

        private void Table_MouseClick(object sender, MouseEventArgs e)
        {
            if (currentTable != null)
            {
                currentTable.Controls["lblName"].BackColor = Color.Transparent;
            }
            currentTable = ((Table)((Control)sender).GetContainerControl());

            currentTable.Controls["lblName"].BackColor = Color.Silver;

            currentTableData = GetCurrentTableRow(currentTable.TableName);
            currentTableData.PosX = currentTable.Location.X;
            currentTableData.PosY = currentTable.Location.Y;

            txtName.Text = currentTableData.TableName;
            txtSeats.Value = currentTableData.NumOfSeats;
            txtNotes.Text = currentTableData.Note;

            rdoStatus.SelectedIndex = currentTableData.Status - 1;
            rdoStatus.Enabled = true;
        }
        #endregion

        private void TablesManagement_Leave(object sender, EventArgs e)
        {
            if (tablesTableAdapter != null && dataSetRA.GetChanges() != null)
                tablesTableAdapter.Update(dataSetRA);
        }

        private void rdoStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((currentTable != null))
            {
                currentTable.Status = (Table.TableStatus)(rdoStatus.SelectedIndex + 1);
                currentTableData.Status = rdoStatus.SelectedIndex + 1;
                if (tablesTableAdapter != null)
                    tablesTableAdapter.Update(dataSetRA);
            }
        }
    }
}
